<?php
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
    'id' => 'resourceForm',
    //   'type'=>'horizontal',
    'htmlOptions' => array('class' => 'well'),
        ));

$model = new ResourceFormModel();
$space_id = Blyn::app()->getActiveSpace()->getId();

$root = 0;
$set = BMResource::model()->findByAttributes(array('space_id' => $space_id, 'level' => 2));
if ($set != null) {
    $root = $set;
} else {
    $target = BMResource::model()->roots()->findAll();

    $newTree = new BMResource;
    $newTree->space_id = $space_id;
    $newTree->name = "Space Root";
    $newTree->folder = 1;
    $appId = intval(Blyn::app()->getActiveApp()->getId());
    $newTree->application_id = $appId;
    $newTree->original_id = 0;
    $newTree->appendTo($target[0]);

    $root = $newTree;
}
?>

<div class="row-fluid">
    <?php
    $this->widget('ext.NestedDynaTree.NestedDynaTree', array(
        //the class name of the model.
        'modelClass' => "BMResource",
        'id' => "resourceTree",
        'rid' => $root->_id,
        // action taken on click on item. (default empty)
        'clickAction' => '',
        'jsActiveAction' => 'activeNode',
        'jsPostInitAction' => 'postInitAction',
        //if given, AJAX load a result of clickAction to the container (default empty)
        'clickAjaxLoadContainer' => '',
        //can insert, delete and ( if enabled)drag&drop (default true) 
        'manipulationEnabled' => !Yii::app()->user->isGuest,
        //can sort items by drag&drop (default true)
        'dndEnabled' => false,
        //AJAX controller absolute path if you don`t use controllerMap
        // 'ajaxController'=>'/path/to/controller/' //default('/AXtree/')
        'ajaxController' => Yii::app()->createUrl("/AXtree") . '/'
    ));
    ?>
</div>

<div class="row-fluid">
    <?php
    $assetUrl = Yii::app()->baseUrl;
    Yii::app()->getClientScript()
            //->registerCoreScript('jquery')
            //->registerCssFile($assetUrl.'/css/prettify.css')
            //->registerCssFile($assetUrl.'/css/bootstrap-combined.no-icons.min.css')
            //->registerCssFile($assetUrl.'/css/bootstrap-responsive.min.css')
            ->registerCssFile($assetUrl . '/css/font-awesome.min.css')
            ->registerScriptFile($assetUrl . '/js/jquery.hotkeys.js')
            ->registerCssFile($assetUrl . '/css/editor.css')
            ->registerScriptFile($assetUrl . '/js/bootstrap-wysiwyg.js');
    ?> 
    <ul class="nav nav-tabs" style="margin-bottom: 15px">
        <li class="active"><a href="#tabNode" data-toggle="tab">Node</a></li>
        <li><a href="#tabFiles" data-toggle="tab">Files</a></li>
    </ul>
    <div class="tab-content">
        <div class="tab-pane active" id="tabNode" style="min-height: 270px">
            <table cellpadding="2">
                <tr><td><b>Current Resource:</b></td><td id="currentNodeName"></td></tr>
                <tr><td><b>Mode:</b></td><td><input type="radio" id="mode0" name="mode" value="0" checked /> Add 
                        &nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" id="mode1" name="mode" value="1" /> Edit</td></tr>
            </table>
            <br />
            <?php
            echo CHtml::beginForm();
            echo $form->textFieldRow($model, 'name', array('class' => 'span5'));
            echo $form->textAreaRow($model, 'description', array('class' => 'span5', 'rows' => 3));
            echo $form->checkBoxRow($model, 'folder', array());
            ?>
            <div>
                <div id="alerts"></div>
                <div class="btn-toolbar" data-role="editor-toolbar" data-target="#editor">
                    <div class="btn-group">
                        <a class="btn dropdown-toggle" data-toggle="dropdown" title="Font"><i class="icon-font"></i><b class="caret"></b></a>
                        <ul class="dropdown-menu">
                        </ul>
                    </div>
                    <div class="btn-group">
                        <a class="btn dropdown-toggle" data-toggle="dropdown" title="Font Size"><i class="icon-text-height"></i>&nbsp;<b class="caret"></b></a>
                        <ul class="dropdown-menu">
                            <li><a data-edit="fontSize 5"><font size="5">Huge</font></a></li>
                            <li><a data-edit="fontSize 3"><font size="3">Normal</font></a></li>
                            <li><a data-edit="fontSize 1"><font size="1">Small</font></a></li>
                        </ul>
                    </div>
                    <div class="btn-group">
                        <a class="btn dropdown-toggle" data-toggle="dropdown" title="Font Color"><i class="icon-dashboard"></i>&nbsp;<b class="caret"></b></a>
                        <ul class="dropdown-menu">
                            <li><a data-edit="foreColor #ff0000" title="Use Red Color">Red</a></li>
                            <li><a data-edit="foreColor #00ff00" title="Use Green Color">Green</a></li>
                            <li><a data-edit="foreColor #0000ff" title="Use Blue Color">Blue</a></li>
                        </ul>
                    </div>
                    <div class="btn-group">
                        <a class="btn" data-edit="bold" title="Bold (Ctrl/Cmd+B)"><i class="icon-bold"></i></a>
                        <a class="btn" data-edit="italic" title="Italic (Ctrl/Cmd+I)"><i class="icon-italic"></i></a>
                        <a class="btn" data-edit="strikethrough" title="Strikethrough"><i class="icon-strikethrough"></i></a>
                        <a class="btn" data-edit="underline" title="Underline (Ctrl/Cmd+U)"><i class="icon-underline"></i></a>
                    </div>
                    <div class="btn-group">
                        <a class="btn" data-edit="insertunorderedlist" title="Bullet list"><i class="icon-list-ul"></i></a>
                        <a class="btn" data-edit="insertorderedlist" title="Number list"><i class="icon-list-ol"></i></a>
                        <a class="btn" data-edit="outdent" title="Reduce indent (Shift+Tab)"><i class="icon-indent-left"></i></a>
                        <a class="btn" data-edit="indent" title="Indent (Tab)"><i class="icon-indent-right"></i></a>
                    </div>
                    <div class="btn-group">
                        <a class="btn" data-edit="justifyleft" title="Align Left (Ctrl/Cmd+L)"><i class="icon-align-left"></i></a>
                        <a class="btn" data-edit="justifycenter" title="Center (Ctrl/Cmd+E)"><i class="icon-align-center"></i></a>
                        <a class="btn" data-edit="justifyright" title="Align Right (Ctrl/Cmd+R)"><i class="icon-align-right"></i></a>
                        <a class="btn" data-edit="justifyfull" title="Justify (Ctrl/Cmd+J)"><i class="icon-align-justify"></i></a>
                    </div>
                    <div class="btn-group">
                        <a class="btn dropdown-toggle" data-toggle="dropdown" title="Hyperlink"><i class="icon-link"></i></a>
                        <div class="dropdown-menu input-append">
                            <input class="span2" placeholder="URL" type="text" data-edit="createLink"/>
                            <button class="btn" type="button">Add</button>
                        </div>
                        <a class="btn" data-edit="unlink" title="Remove Hyperlink"><i class="icon-cut"></i></a>

                    </div>

                    <div class="btn-group">
                        <a class="btn" data-edit="undo" title="Undo (Ctrl/Cmd+Z)"><i class="icon-undo"></i></a>
                        <a class="btn" data-edit="redo" title="Redo (Ctrl/Cmd+Y)"><i class="icon-repeat"></i></a>
                    </div>
                </div>

                <div id="editor">

                </div>
            </div>
            <br />    
            <?php
            echo CHtml::button('Add', array('type' => "button", "id" => "saveButton"));
            echo CHtml::button('Delete', array('type' => "button", "id" => "deleteButton", "style" => "display:none"));
            echo CHtml::endForm();
            ?>
        </div>
        <div class="tab-pane" id="tabFiles" style="min-height: 270px">
            <table cellpadding="2">
                <tr><td><b>Current Resource:</b></td><td id="currentResNodeName"></td></tr>
            </table>
            <br />
            <div>
                <?php
                $uploadModel = new XUploadResourceForm;

                $uploadWidget = $this->widget('xupload.XUpload', array(
                    'url' => Yii::app()->createUrl("site/uploadResource", array("parent_id" => 1)),
                    'model' => $uploadModel,
                    'attribute' => 'file',
                    'multiple' => true,
                    'formView' => 'application.views.site.form',
                    'uploadView' => 'application.views.site.upload',
                    'downloadView' => 'application.views.site.download',
                    'options' => array(//Additional javascript options
                        //This is the submit callback that will gather
                        //the additional data  corresponding to the current file
                        'submit' => 'js:function (e, data) {
                var inputs = data.context.find(":input");
                data.formData = inputs.serializeArray();
                data.url = this.getAttribute("action");
                return true;
            }'
                    ),
                ));

                Yii::app()->getClientScript()->registerScript(__CLASS__ . $this->id, '
        var htmlIdPrefix = "ResourceFormModel_";
        
        function setMode(mode) {
            var node = $("#resourceTree").dynatree("getActiveNode");
            if (mode == 0) { //add mode
                initAddMode(node);
            } else { //edit mode
                getNodeData(node, initEditMode);
            }
        }
		
		function getResourceItems(id) {
			$.get("' . Yii::app()->createUrl("site/uploadResource", array("_method" => "get")) . '/parent_id/" + id,
				function(result){
					var data = {result: result};
					showResourceItems(data);
				 },"json");
		}
		
		function showResourceItems(data) {
			$("#' . $uploadWidget->htmlOptions["id"] . ' table tbody tr.template-download").remove();
			$("#' . $uploadWidget->htmlOptions["id"] . ' table tbody tr.template-upload").remove();

			var form = $("#' . $uploadWidget->htmlOptions["id"] . '");
			var that = form.data("fileupload");

			var template;
			if (data.context) {
				data.context.each(function (index) {
					var file = ($.isArray(data.result) &&
							data.result[index]) || {error: "emptyResult"};
					if (file.error) {
						that._adjustMaxNumberOfFiles(1);
					}
					that._transition($(this)).done(
						function () {
							var node = $(this);
							template = that._renderDownload([file])
								.css("height", node.height())
								.replaceAll(node);
							that._forceReflow(template);
							that._transition(template).done(
								function () {
									data.context = $(this);
									that._trigger("completed", null, data);
								}
							);
						}
					);
				});
			} else {
				template = that._renderDownload(data.result)
					.appendTo(that.options.filesContainer);
				that._forceReflow(template);
				that._transition(template).done(
					function () {
						data.context = $(this);
						that._trigger("completed", null, data);
					}
				);
			}
		}

        function activeNode(node) {
            var mode = parseInt($("input:radio[name=mode]:checked").val());
            setMode(mode);
            
            $("#currentResNodeName").html(node.data.title);
            initUploadUrl(node.data.key);

			getResourceItems(node.data.key);
        }
        
        function postInitAction(isReloading, isError) {
            if (!isError) {
                window.setTimeout(function() {
                    var rootNode = $("#resourceTree").dynatree("getRoot").getChildren()[0];
                    rootNode.activate();
                 }, 100);
            }
        }
        
        function initAddMode(node) {
            $("#currentNodeName").html(node.data.isFolder ? node.data.title : node.getParent().data.title);

            $("#" + htmlIdPrefix + "name").val("");
            $("#" + htmlIdPrefix + "description").val("");
            $("#" + htmlIdPrefix + "folder").attr("checked", false);
            $("#" + htmlIdPrefix + "folder").removeAttr("disabled");
            
            //$("#" + htmlIdPrefix + "data").val("");
            $("#editor").html("");
            
            $("#saveButton").val("Add");
            $("#deleteButton").hide();
        }
        
        function initEditMode(node, data) {
            $("#currentNodeName").html(node.data.title);
            
            $("#" + htmlIdPrefix + "name").val(data.name);
            $("#" + htmlIdPrefix + "description").val(data.description);
            $("#" + htmlIdPrefix + "folder").attr("checked", data.folder > 0 ? true : false);
            $("#" + htmlIdPrefix + "folder").attr("disabled","disabled");
            
            //$("#" + htmlIdPrefix + "data").val(data.data);
            $("#editor").html(data.data);
            $("#saveButton").val("Update");
            
            var rootNode = $("#resourceTree").dynatree("getRoot").getChildren()[0];
            if (rootNode == node) {
                $("#deleteButton").hide();
            } else {
                $("#deleteButton").show();
            }
        }
        
        $("#saveButton").click(function(){
            var data = {
                space_id: ' . $space_id . ',
                name: $("#" + htmlIdPrefix + "name").val(),
                description: $("#" + htmlIdPrefix + "description").val(),
                folder: $("#" + htmlIdPrefix + "folder").attr("checked") == "checked" ? 1 : 0,
                data: $("#editor").html() //$("#" + htmlIdPrefix + "data").val()
            };
            
            if ($("#saveButton").val() === "Add") {
                addResourceButtonClick(data);
            } else {
                updateResourceButtonClick(data);
            }
        });
        
        $("#deleteButton").click(function(){
            deleteResourceButtonClick();
        });
        
        $("#mode0").click(function(){
            setMode(0);
        });
        
        $("#mode1").click(function(){
            setMode(1);
        });

        $("#editor").wysiwyg();
        
        function initUploadUrl(id) {
            var form = $("#' . $uploadWidget->htmlOptions["id"] . '")[0];
            var action = form.getAttribute("action");
            var pos = action.lastIndexOf("/");
            if (pos != -1) {
                action = action.substr(0, pos + 1) + id;
            } else {
                action += "/" + id;
            }
            
            form.setAttribute("action", action);
        }
    ');
                ?>
            </div>
            <br />
        </div>
    </div>
</div>

<?php $this->endWidget(); ?>
